package com.yixun.qfbao.controller;

import com.alibaba.excel.EasyExcel;
import com.yixun.qfbao.api.service.AssistantReportService;
import com.yixun.qfbao.api.service.CPService;
import com.yixun.qfbao.api.service.ChannelReportService;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.common.model.PageDTO;
import com.yixun.qfbao.dto.*;
import com.yixun.qfbao.dto.base.BaseRequestDTO;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.exception.ResponseCode;
import com.yixun.qfbao.model.AgencyPremisesSalesReport;
import com.yixun.qfbao.model.ChannelCooOrgAgentReport;
import com.yixun.qfbao.model.ChannelCooOrgReport;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.util.StringUtil;
import com.yixun.qfbao.utils.DateStyle;
import com.yixun.qfbao.utils.DateUtils;
import com.yixun.qfbao.utils.LoginUtils;
import com.yixun.qfbao.xf.model.dto.CustomerPremisesDto;
import com.yixun.qfbao.xf.model.enums.ConfirmStatusEnum;
import com.yixun.qfbao.xf.model.enums.MortgageStatusEnum;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Controller
@ResponseBody
@RequestMapping("/api/channelreport")
@Api(tags = {"渠道报表"})
public class ChannelReportController {

    @Autowired
    LoginUtils loginUtils;
    @Autowired
    PartnerInfoService partnerInfoService;
    @Autowired
    ChannelReportService channelReportService;
    @Autowired
    AssistantReportService assistantReportService;
    @Autowired
    private CPService cpService;

    @ApiOperation(notes = "渠道合作机构报表", value="渠道合作机构报表")
    @PostMapping("/getChannelCooOrgReport")
    public BaseResponseDTO<ChannelCooOrgReportResDto> getChannelCooOrgReport(@RequestBody BaseRequestDTO<ChannelCooOrgReportReqDto> reqDto) throws ParseException {
        BaseResponseDTO<ChannelCooOrgReportResDto> response = new BaseResponseDTO<>();
        if(Objects.isNull(reqDto.getParams().getUserId())){
            response.setResult(ResponseCode.PARAM_INVALID.getCode());
            response.setErrorMsg(String.format(ResponseCode.PARAM_INVALID.getMessageTemplate(), "用户丢失,"));
            return response;
        }
        PageDTO pageDTO = new PageDTO();
        pageDTO.setPageNum(reqDto.getParams().getPageNo());
        pageDTO.setPageSize(reqDto.getParams().getPageSize());
        ChannelCooOrgReportResDto resDto = channelReportService.getChannelCooOrgReport(reqDto.getParams(), pageDTO);
        response.setResult(ResultEnum.SUCCESS.getNo());
        response.setErrorMsg(ResultEnum.SUCCESS.getDes());
        response.setResData(resDto);
        return response;
    }

    @GetMapping(value = "/exportChannelCooOrgReport")
    @ApiOperation(value = "导出渠道合作机构报表")
    public void exportChannelCooOrgReport(ChannelCooOrgReportReqDto reqDto, HttpServletResponse response) throws IOException, ParseException {
        if(Objects.isNull(reqDto.getUserId())){
            return;
        }
        PageDTO pageDTO = new PageDTO();
        pageDTO.setPageNum(PageDTO.DEFAULT_PAGENUM);
        pageDTO.setPageSize(PageDTO.MAX_PAGESIZE);
        ChannelCooOrgReportResDto resDto = channelReportService.getChannelCooOrgReport(reqDto, pageDTO);
        List<ChannelCooOrgReport> reportList = resDto.getPageModel().getRows();
        List<ChannelCooOrgReportExport> exportList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(reportList)){
            Map<Long, String> deptMap = reportList.stream()
                    .collect(Collectors.toMap(ChannelCooOrgReport::getDeptId, ChannelCooOrgReport::getDeptName, (oldValue, newValue) -> newValue));

            for(ChannelCooOrgReport report: reportList){
                ChannelCooOrgReportExport exportData = new ChannelCooOrgReportExport();
                BeanUtils.copyProperties(report, exportData);
                String deptName = "";
                if(StringUtils.isNotBlank(report.getPermissionCode())){
                    String [] pcArr = report.getPermissionCode().split("-");
                    for(int ii=0; ii<pcArr.length; ii++){
                        if(StringUtils.isBlank(deptMap.get(Long.valueOf(pcArr[ii])))){
                            continue;
                        }
                        deptName += deptMap.get(Long.valueOf(pcArr[ii]));
                        if(ii != (pcArr.length - 1) && StringUtils.isNotBlank(deptName)){
                            deptName += "/";
                        }
                    }
                }else{
                    deptName = report.getDeptName();
                }
                exportData.setDeptName(deptName);
                exportList.add(exportData);
            }
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=渠道合作机构报表.xlsx");
        EasyExcel.write(response.getOutputStream(), ChannelCooOrgReportExport.class).sheet("渠道合作机构报表").doWrite(exportList);
    }

    @ApiOperation(notes = "渠道合作机构经纪人报表", value="渠道合作机构经纪人报表")
    @PostMapping("/getChannelCooOrgAgentReport")
    public BaseResponseDTO<ChannelCooOrgAgentReportResDto> getChannelCooOrgAgentReport(@RequestBody BaseRequestDTO<ChannelCooOrgAgentReportReqDto> reqDto) throws ParseException {
        BaseResponseDTO<ChannelCooOrgAgentReportResDto> response = new BaseResponseDTO<>();
        if(Objects.isNull(reqDto.getParams().getUserId())){
            response.setResult(ResponseCode.PARAM_INVALID.getCode());
            response.setErrorMsg(String.format(ResponseCode.PARAM_INVALID.getMessageTemplate(), "用户丢失,"));
            return response;
        }
        PageDTO pageDTO = new PageDTO();
        pageDTO.setPageNum(reqDto.getParams().getPageNo());
        pageDTO.setPageSize(reqDto.getParams().getPageSize());
        ChannelCooOrgAgentReportResDto resDto = channelReportService.getChannelCooOrgAgentReport(reqDto.getParams(), pageDTO);
        response.setResult(ResultEnum.SUCCESS.getNo());
        response.setErrorMsg(ResultEnum.SUCCESS.getDes());
        response.setResData(resDto);
        return response;
    }

    @GetMapping(value = "/exportChannelCooOrgAgentReport")
    @ApiOperation(value = "导出渠道合作机构经纪人报表")
    public void exportChannelCooOrgAgentReport(ChannelCooOrgAgentReportReqDto reqDto, HttpServletResponse response) throws IOException, ParseException {
        if(Objects.isNull(reqDto.getUserId())){
            return;
        }
        PageDTO pageDTO = new PageDTO();
        pageDTO.setPageNum(PageDTO.DEFAULT_PAGENUM);
        pageDTO.setPageSize(PageDTO.MAX_PAGESIZE);
        ChannelCooOrgAgentReportResDto resDto = channelReportService.getChannelCooOrgAgentReport(reqDto, pageDTO);
        List<ChannelCooOrgAgentReport> reportList = resDto.getPageModel().getRows();
        List<ChannelCooOrgAgentReportExport> exportList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(reportList)){
            Map<Long, String> deptMap = reportList.stream()
                    .collect(Collectors.toMap(ChannelCooOrgAgentReport::getDeptId, ChannelCooOrgAgentReport::getDeptName, (oldValue, newValue) -> newValue));

            for(ChannelCooOrgAgentReport report: reportList){
                ChannelCooOrgAgentReportExport exportData = new ChannelCooOrgAgentReportExport();
                BeanUtils.copyProperties(report, exportData);
                String deptName = "";
                if(StringUtils.isNotBlank(report.getPermissionCode())){
                    String [] pcArr = report.getPermissionCode().split("-");
                    for(int ii=0; ii<pcArr.length; ii++){
                        if(StringUtils.isBlank(deptMap.get(Long.valueOf(pcArr[ii])))){
                            continue;
                        }
                        deptName += deptMap.get(Long.valueOf(pcArr[ii]));
                        if(ii != (pcArr.length - 1) && StringUtils.isNotBlank(deptName)){
                            deptName += "/";
                        }
                    }
                }else{
                    deptName = report.getDeptName();
                }
                exportData.setDeptName(deptName);
                exportList.add(exportData);
            }
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=渠道合作机构经纪人报表.xlsx");
        EasyExcel.write(response.getOutputStream(), ChannelCooOrgAgentReportExport.class).sheet("渠道合作机构经纪人报表").doWrite(exportList);
    }


    @GetMapping(value = "exportAssistantReport")
    @ApiOperation(value = "导出报备列表")
    public void exportAssistantReport(AssistantReportPageReqDto reqDto, HttpServletResponse response) throws IOException, ParseException {
        reqDto.setPageNo(1);
        reqDto.setPageSize(PageDTO.MAX_PAGESIZE);
        AssistantReportPageResDto resDto = assistantReportService.getAssistantReportPage(reqDto);
        List<CustomerPremisesDto> reportList = resDto.getCpDtoPage().getRows();
        List<AssistantReportExport> exportList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(reportList)){
            for(CustomerPremisesDto report: reportList){
                exportList.add(convertReportToExportData(report));
            }
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=报备导出.xlsx");
        EasyExcel.write(response.getOutputStream(), AssistantReportExport.class).sheet("报备导出").doWrite(exportList);
    }

    @GetMapping(value = "exportCPPage")
    @ApiOperation(value = "导出巧分销报备列表")
    public void exportCPPage(GetCPPageReqDto reqDto, HttpServletResponse response) throws IOException, ParseException {
        reqDto.setPageNo(1);
        reqDto.setPageSize(PageDTO.MAX_PAGESIZE);
        PartnerInfo pi = loginUtils.getUser(reqDto.getUserId());
        reqDto.setAccountType(pi.getAccountType());
        reqDto.setMerchantId(pi.getHigherid());
        Long groupId = reqDto.getGroupId();
        if(groupId != null) {
            reqDto.setStoreOrGroupId(groupId);
        }
        GetCPPageResDto resDto = cpService.getCPPage(reqDto);
        List<CustomerPremisesDto> reportList = resDto.getCpDtoPage().getRows();
        List<CPPageReportExport> exportList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(reportList)){
            for(CustomerPremisesDto report: reportList){
                exportList.add(convertCPReportToExportData(report));
            }
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=巧分销报备导出.xlsx");
        EasyExcel.write(response.getOutputStream(), CPPageReportExport.class).sheet("巧分销报备列表").doWrite(exportList);
    }

    private AssistantReportExport convertReportToExportData(CustomerPremisesDto report){
        AssistantReportExport exportData = new AssistantReportExport();
        try {
            exportData.setPremisesName(report.getPremisesName());
            exportData.setName(report.getName());
            exportData.setMobile(report.getMobile());
            exportData.setReportType(report.getReportType());
            exportData.setReportUserName(report.getStaffName());
            exportData.setReportUserPhone(report.getStaffPhone());
            if ("案场代报备".equals(report.getReportType())) {
                exportData.setReportUserName(report.getAssistantName());
                exportData.setReportUserPhone(report.getAssistantPhone());
            }
            exportData.setCustomerStatusName(report.getCusNewStatusName());
            exportData.setConfirmStatusName(ConfirmStatusEnum.getDescByNo(report.getConfirmStatus()));
            exportData.setMortgageStatusName(MortgageStatusEnum.getDescByNo(report.getMortgageStatus()));
            exportData.setStaffCompanyName(report.getStaffCompanyName());
            exportData.setStaffStoreName(report.getStaffStoreName());
            exportData.setStaffDepartmentName(report.getStaffDepartmentName());
            exportData.setStaffName(report.getStaffName());
            exportData.setStaffPhone(report.getStaffPhone());
            exportData.setPrincipalName(report.getPrincipalName());
            exportData.setPrincipalPhone(report.getPrincipalPhone());
            exportData.setCreateTime(DateUtils.DateToString(report.getCreateTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            exportData.setHoptVisitTime(DateUtils.DateToString(report.getHopeVisitTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            exportData.setVisitTime(DateUtils.DateToString(report.getVisitTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            exportData.setIsRepeatVisit(report.getVisitState());
            exportData.setRecommenderName(report.getRecommenderName());
            exportData.setRecommenderPhone(report.getRecommenderPhone());
            exportData.setBuildingName(report.getBuildingName());
            exportData.setRoomName(report.getRoomName());
            exportData.setPayFinish("否");
            if("1".equals(report.getPayFinish())){
                exportData.setPayFinish("是");
            }
            exportData.setSubscribeTime(DateUtils.DateToString(report.getSubscribeTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            exportData.setSignatureAmount(Objects.isNull(report.getSignatureAmount())?"":report.getSignatureAmount().toString());
            exportData.setValuationArea(Objects.isNull(report.getValuationArea())?"":report.getValuationArea().toString());
            exportData.setSignTime(DateUtils.DateToString(report.getSignTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            exportData.setDealAmount(Objects.isNull(report.getDealAmount())?"":report.getDealAmount().toString());
            exportData.setRemark(report.getRemark());
        }catch (Exception ex){
            log.error("export assistant report, convertReportToExportData report: {}, error: {}", report, ex);
        }
        return exportData;
    }

    private CPPageReportExport convertCPReportToExportData(CustomerPremisesDto report){
        CPPageReportExport exportData = new CPPageReportExport();
        try {
            exportData.setPremisesName(report.getPremisesName());
            exportData.setName(report.getName());
            exportData.setMobile(report.getMobile());
            exportData.setReportType(report.getReportType());
            exportData.setReportUserName(report.getStaffName());
            exportData.setReportUserPhone(report.getStaffPhone());
            exportData.setCustomerStatusName(report.getCusNewStatusName());
            exportData.setConfirmStatusName(ConfirmStatusEnum.getDescByNo(report.getConfirmStatus()));
            exportData.setMortgageStatusName(MortgageStatusEnum.getDescByNo(report.getMortgageStatus()));
            exportData.setStaffCompanyName(report.getStaffCompanyName());
            exportData.setStaffDepartmentName(report.getStaffDepartmentName());
            exportData.setStaffName(report.getStaffName());
            exportData.setStaffPhone(report.getStaffPhone());
            exportData.setPrincipalName(report.getPrincipalName());
            exportData.setPrincipalPhone(report.getPrincipalPhone());
            exportData.setCreateTime(DateUtils.DateToString(report.getCreateTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            exportData.setPayFinish("否");
            if("1".equals(report.getPayFinish())){
                exportData.setPayFinish("是");
            }
        }catch (Exception ex){
            log.error("export CPPage report, convertReportToExportData report: {}, error: {}", report, ex);
        }
        return exportData;
    }

}
